<template>
  <Dialog title="查看" v-model="dialogVisible">
    <div class="basic-info">
      <h3 class="info-title">基本信息</h3>
      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">序列号：</span>
          <span class="info-content">{{ formData.serialNo }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">工单日期：</span>
          <span class="info-content">{{ dateFormatter(null, null, formData.docDate) }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">工单数量：</span>
          <span class="info-content">{{ formData.planQty }}</span>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">关联工序：</span>
          <span class="info-content">{{ formData.processCode }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">物料品号：</span>
          <span class="info-content">{{ formData.materialsNum }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">物料名称：</span>
          <span class="info-content">{{ formData.itemName }}</span>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">物料规格：</span>
          <span class="info-content">{{ formData.itemSpecification }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">物料品牌：</span>
          <span class="info-content">{{ formData.brand }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">检验人员</span>
          <span class="info-content">{{ formData.creatorName }}</span>
        </div>
      </div>
      <div class="info-grid">
        <div class="info-row">
          <span class="info-label">检测结果：</span>
          <span class="info-content">{{
            getStrDictOptions(DICT_TYPE.DETECTION_RESULT).find(
              (item) => item.value == formData.status
            )?.label
          }}</span>
        </div>
        <div class="info-row">
          <span class="info-label">检验记录编号：</span>
          <span class="info-content">{{ formData.recordCode }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">关联工单号：</span>
          <span class="info-content">{{ formData.docNo }}</span>
        </div>
      </div>
    </div>
    <div class="basic-table">
      <div style="display: flex">
        <h3 class="info-title">检测详情</h3>
        <el-form-item label="检验类别:" prop="typeId" style="margin-left: 10px; margin-top: -5px">
          <el-select v-model="detectionType" placeholder="请选择检测类型" class="!w-100px">
            <el-option
              v-for="dict in paramsTypes"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <div
        v-if="metricsTitles.length > 0 && metricsItemTableData.length > 0"
        class="inspection-table"
      >
        <div class="table-scroll-wrapper">
          <table class="custom-table">
            <thead>
              <tr>
                <!-- 左上角斜线单元格 -->
                <th class="sticky-header sticky-column diagonal-header" style="z-index: 99">
                  <!-- <div class="top-text">检测项目名称</div>
                <div class="bottom-text">检测值录入</div> -->
                  <img src="/src/assets/imgs/tab.png" alt="" style="width: 100%; height: 100%" />
                </th>
                <!-- 动态列头 -->
                <th v-for="(col, colIndex) in metricsTitles" :key="colIndex" class="sticky-header">
                  {{ col }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, rowIndex) in metricsItemTableData" :key="rowIndex">
                <td class="label-cell sticky-column">
                  <span>{{ row.label }}</span>
                  <!--<el-icon class="edit-icon"  @click="editRow(row)">
                  <Edit />
                </el-icon>-->
                </td>
                <td v-for="(item, colIndex) in row.values" :key="colIndex">
                  <el-input
                    v-if="checkShowInput(item)"
                    v-model="row.values[colIndex]"
                    :class="getCellClass(row.statuses[colIndex])"
                    :disabled="true"
                  />
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <template #footer>
      <!-- <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button> -->
      <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InspectionRecordApi, InspectionRecordVO } from '@/api/opticore/inspection/record'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'

/** 检验记录 表单 */
defineOptions({ name: 'InspectionRecordForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  serialNo: undefined,
  recordCode: undefined,
  docNo: undefined,
  materialsNum: undefined,
  typeId: undefined,
  lineId: undefined,
  processCode: undefined,
  status: undefined,
  remark: undefined,
  creatorName: undefined,
  planQty: undefined,
  itemSpecification: undefined,
  itemName: undefined,
  brand: undefined,
  docDate: undefined
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const detectionType = ref('')
const paramsTypes = ref([])

const metricsTitles = ref([])
const metricsItemTableData = ref([])

const recordId: number = ref('')

// 检查是否显示输入框
const checkShowInput = (value) => {
  if (value) return true
  return false
  //return metricsItemTableData.value[rowIndex].values && metricsItemTableData.value[rowIndex].values[colIndex] !== undefined
}

// 获取单元格样式
const getCellClass = (status: string) => {
  if (status === 'NG') return 'cell-red'
  if (status === 'OK') return 'cell-green'
  return ''
}

/** 初始化 **/
onMounted(() => {
  paramsTypes.value = getStrDictOptions(DICT_TYPE.ARGS_VALUE_TYPE)
  detectionType.value = paramsTypes.value[0]
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  recordId.value = id
  resetForm()
  // 修改时，设置数据
  if (id) {
    try {
      await fetchMetricsData(detectionType.value.value)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const fetchMetricsData = async (type: string) => {
  const response = await InspectionRecordApi.getInspectionRecord(recordId.value, type)
  formData.value = response
  const details = response.detailsRespVOS
  if (!details || details.length === 0) {
    metricsTitles.value = []
    metricsItemTableData.value = []
    return
  }
  // 确保第一条记录存在且有itemNames
  if (!details[0] || !details[0].itemNames) {
    metricsTitles.value = []
    metricsItemTableData.value = []
    return
  }
  metricsTitles.value = details[0].itemNames || []
  console.log('metricsTitles:', metricsTitles.value)
  metricsItemTableData.value = details.map((detail) => ({
    label: detail.label,
    statuses: detail.statuses,
    values: detail.values
  }))
  console.log(metricsItemTableData.value)
}

watch(detectionType, (newVal, oldVal) => {
  if (newVal !== oldVal && oldVal !== '') {
    fetchMetricsData(newVal)
  }
})

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InspectionRecordVO
    if (formType.value === 'create') {
      await InspectionRecordApi.createInspectionRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await InspectionRecordApi.updateInspectionRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNo: undefined,
    recordCode: undefined,
    orderCode: undefined,
    materialsNum: undefined,
    typeId: undefined,
    lineId: undefined,
    processId: undefined,
    status: undefined,
    remark: undefined,
    creatorName: undefined
  }
  formRef.value?.resetFields()
  detectionType.value = paramsTypes.value[0].value
}

const tableData = [
  {
    date: '2016-05-03',
    name: 'Tom',
    address: 'No. 189, Grove St, Los Angeles'
  }
]
</script>

<style scope>
.basic-info {
  font-family: Arial, sans-serif;
  padding: 20px;

  border-radius: 8px;
}

.basic-table {
  padding: 20px;
}

.el-table th {
  background-color: #f6f8fa !important;
}

.info-title {
  font-size: 18px;
  margin-bottom: 20px;
  color: #333;
}

.info-grid {
  display: flex;
  /* justify-content: space-between; */
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
}

.info-row {
  /* flex: 1; */
  width: 33.3%;
  display: flex;
  margin-right: 10px;
}

.info-label {
  font-weight: bold;
  color: #666;
  min-width: 100px;
}

.info-content {
  color: #333;

  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 文字溢出隐藏 */
  text-overflow: ellipsis; /* 出现省略号 */
}

.view-link {
  color: #1890ff;
  text-decoration: none;
  margin-left: 5px;
  cursor: pointer;
}

.other-info {
  margin-top: 15px;
}

.other-info .info-content {
  word-break: break-word;
}

.inspection-table {
  width: 100%;
  margin-top: -10px;
}

/* ✅ 固定宽高的滚动容器 */
.table-scroll-wrapper {
  max-height: 600px; /* 你想固定的表格显示高度 */
  max-width: 100%; /* 或设置成 800px 等固定值 */
  overflow: auto; /* 水平 + 垂直都可以滚动 */
  border: 1px solid #ccc;
}

/* 表格本体 */
.custom-table {
  width: 100%;
  min-width: 600px; /* 保证有横向滚动空间 */
  border-collapse: collapse;
  table-layout: fixed;
  text-align: center;
}

/* 表头、单元格基本样式 */
.custom-table th {
  border: 1px solid #ccc;
  /* padding: 4px; */
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */
}

.custom-table td {
  border: 1px solid #ccc;
  height: 60px;
  padding-left: 30px;
  padding-right: 30px;
  text-align: center;
  white-space: nowrap; /* 不换行，确保横向可滚 */

  .el-input__wrapper {
    border: 1px solid #070707;
  }
}

.custom-table td .el-input__inner {
  border-width: 2px;
  border-color: #409eff;
}

/* 确保下拉菜单显示在最上层 */
.el-select__popper {
  z-index: 100000 !important;
}

/* 斜线表头 */
.diagonal-header {
  width: 15%;
  position: sticky;
  height: 60px;
  background: #ddd;
  padding: 0;
  z-index: 99999;
  overflow: hidden;
}

/* .diagonal-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: var(--diagonal-width, 104%);
  height: 100%;
  border-top: 1px solid #666;
  transform: rotate(var(--diagonal-angle, 13deg));
  transform-origin: top left;
  z-index: 1;
} */

/* 文本放角落 */
.top-text {
  position: absolute;
  top: 4px;
  right: 6px;
  font-size: 16px;
  z-index: 2;
}

.bottom-text {
  position: absolute;
  bottom: 4px;
  left: 6px;
  font-size: 16px;
  z-index: 2;
}

/* ✅ 表头固定（非左上） */
.sticky-header {
  position: sticky;
  top: 0;
  background: #f8f8f8;
  z-index: 10;
}

/* ✅ 左侧 label 固定列 */
.sticky-column {
  position: sticky;
  left: 0;
  background: #f9f9f9;
  z-index: 20;
}

/* 编辑图标 */
.label-cell {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 8px;
  font-weight: bold;
}

.edit-icon {
  cursor: pointer;
  font-size: 16px;
}

/* 边框高亮 */
.cell-red .el-input__wrapper {
  border: 1px solid #f56c6c !important;
  background-color: #fef0f0;
}

.cell-green .el-input__wrapper {
  border: 1px solid #67c23a !important;
  background-color: #f0f9eb;
}
</style>
